package com.woniuxy.controller;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.woniuxy.common.entity.ChatMessage;

import com.woniuxy.entity.DTO.ChatWebDTO;
import com.woniuxy.entity.DTO.MessageListDTO;
import com.woniuxy.service.MessageService;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;


// 历史消息控制器
@RestController
@RequestMapping("messages")
public class MessageController {

    @Autowired
    private MessageService messageService;
    //查询历史消息
    @GetMapping("/history")
    public ResponseEntity<List<ChatMessage>> getChatHistory(
            @RequestParam("userId1") String userId1,
            @RequestParam("userId2") String userId2,
            @RequestParam(name = "page",defaultValue = "0") int page,
            @RequestParam(name = "size",defaultValue = "50") int size) {

//        Pageable pageable = PageRequest.of(page, size, Sort.by("timestamp").descending());

        List<ChatMessage> messages = messageService.findConversation(userId1, userId2);

        return ResponseEntity.ok(messages);
    }
    //获取消息列表信息
    @GetMapping("/messagelist")
    public ResponseEntity<List<MessageListDTO>> getMessageList(@RequestParam("userId") String userId) {
        List<MessageListDTO> messageList = messageService.getMessageList(userId);
        return ResponseEntity.ok(messageList);
    }
    @PutMapping("/markAsRead/{messageId}")
    public ResponseEntity<Void> markMessageAsRead(@PathVariable("messageId") Long messageId) {
        // 使用MyBatis-Plus的LambdaUpdateWrapper更新消息状态
        boolean success = messageService.update(
                new LambdaUpdateWrapper<ChatMessage>()
                        .eq(ChatMessage::getId, messageId)
                        .set(ChatMessage::getStatus, ChatMessage.MessageStatus.READ)
        );

        return success ? ResponseEntity.ok().build() : ResponseEntity.notFound().build();
    }
    //web端返回聊天消息
    @GetMapping("/messagelistWeb")
    public ResponseEntity<List<ChatWebDTO>> messagelistWeb(@RequestParam("userId") String userId) {
        List<ChatWebDTO> messagelistWeb = messageService.messagelistWeb(userId);
        return ResponseEntity.ok(messagelistWeb);
    }
}
